package org.syncsoft.overalt.gui.api.componentPlugin;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JList;

import org.syncsoft.overalt.domain.common.entity.IEntity;
import org.syncsoft.overalt.gui.api.WindowContextValue;
import org.syncsoft.overalt.gui.api.listDataModel.AbstractEntityListDataModel;

/**
 * 
 * @author tptfc
 *
 */
public abstract class AbstractEntityListComponentPlugin<T extends AbstractEntityListDataModel<U>, U extends IEntity> implements IComponentPlugin {
	private Map<String, JList> lists;
	private Map<String, T> listsDataModels;
	
	{
		setLists(new HashMap<String, JList>());
		setListsDataModels(new HashMap<String, T>());
	}
	
	protected abstract T doCreateDataModel(Collection<U> entities);
	
	@Override
	public void buildContext(WindowContextValue context) {
		if (context != null) {
			for (String key : getLists().keySet()) {
				JList list = getList(key);
				
				for (int index : list.getSelectedIndices()) {
					U entity = getEntity(key, index);
					
					if (entity != null) {
						context.addMultiValue(key, entity.getCode());
					}
				}
			}
		}
	}

	@Override
	public WindowContextValue getContext() {
		WindowContextValue context = new WindowContextValue();
		buildContext(context);
		return context;
	}
	
	public JList newList(String key, Collection<U> entities) {
		JList list = new JList(createDataModel(key, entities));
		
		getLists().put(key, list);
		return list;
	}
	
	
	/**
	 * 
	 * @param key
	 * @return
	 */
	public JList getList(String key) {
		return getLists().get(key);
	}
	
	/**
	 * 
	 * @param key
	 * @param index
	 * @return
	 */
	public U getEntity(String key, int index) {
		U entity = null;
		
		T dataModel = getListsDataModels().get(key);
		
		if (dataModel != null) {
			entity = dataModel.getEntity(index);
			
		}
		
		return entity;
	}
	
	/**
	 * 
	 * @param key
	 * @param entities
	 * @return
	 */
	protected T createDataModel(String key, Collection<U> entities) {
		T dataModel = doCreateDataModel(entities);
		
		getListsDataModels().put(key, dataModel);
		
		return dataModel;
	}

	protected Map<String, JList> getLists() {
		return lists;
	}

	protected void setLists(Map<String, JList> lists) {
		this.lists = lists;
	}

	protected Map<String, T> getListsDataModels() {
		return listsDataModels;
	}

	protected void setListsDataModels(Map<String, T> listsDataModels) {
		this.listsDataModels = listsDataModels;
	}
}
